package cn.kaguyaever.web;

import cn.kaguyaever.entity.*;
import cn.kaguyaever.service.*;
import cn.kaguyaever.service.impl.*;
import cn.kaguyaever.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    private VoteService voteService = new VoteServiceImpl();

    private JudgeService judgeService = new JudgeServiceImpl();

    private CandidateService candidateService = new CandidateServiceImpl();

    private ProjectService projectService = new ProjectServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());
        if(token!=null&&token.equalsIgnoreCase(code)) {
            //调用登录业务
            User loginUser = userService.login(user);
            //如果loginUser等于null登录失败
            if (loginUser == null) {
                //将错误信息保存在Request域中
                //跳回登录页面
                req.setAttribute("msg", "用户名或密码错误！");
                req.setAttribute("username", username);
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            } else {
                //登录成功
                Project project = projectService.queryProjectByUserId(loginUser.getId());
                req.getSession().setAttribute("user",loginUser);
                if(project!=null) {
                    req.getSession().setAttribute("project", project);
                    String projectId = project.getProjectId();
                    List<Vote> votes = voteService.queryAllVote(project.getProjectId());
                    if(votes!=null) {
                        for(Vote vote:votes){
                            if(vote.getVoteStatus()==0||vote.getVoteStatus()==1){
                                req.getSession().setAttribute("voteId",vote.getVoteId());
                                break;
                            }
                        }
                        for(Vote vote:votes){
                            if(vote.getVoteStatus()==1){
                                req.getSession().setAttribute("voting",vote);
                                break;
                            }
                        }
                        req.getSession().setAttribute("votes", votes);
                    }
                }
                req.getRequestDispatcher("/user/home.jsp").forward(req,resp);
            }
        }else {
            //错误信息保存到Request域中
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());
        if(token!=null&&token.equalsIgnoreCase(code)) {
            if (userService.existsUsername(username)) {
                req.setAttribute("msg", "用户名已存在！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);
                req.getRequestDispatcher("/regist.jsp").forward(req, resp);
            } else {
                userService.registerUser(user);
                req.setAttribute("msg","注册成功请登录");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } else {
            //错误信息保存到Request域中
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.getRequestDispatcher("/regist.jsp").forward(req, resp);
        }
    }

    protected void changePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("password");
        User user = (User)req.getSession().getAttribute("user");
        userService.changePassword(password,user.getId());
        req.setAttribute("msg","修改密码成功");
        user.setPassword(password);
        req.getSession().setAttribute("user",user);
        req.getRequestDispatcher("/user/home.jsp").forward(req, resp);
    }

    protected void judgeLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String projectId = req.getParameter("projectId");
        String code = req.getParameter("code");
        Judge judge = new Judge(null,username,password,1,projectId);
        Project project = projectService.queryProject(projectId);
        if(token!=null&&token.equalsIgnoreCase(code)) {
            Judge loginUser = judgeService.judgeLogin(judge);
            if(project!=null) {
                if (loginUser == null) {
                    //将错误信息保存在Request域中
                    //跳回登录页面
                    req.setAttribute("msg", "用户名或密码错误！");
                    req.setAttribute("username", username);
                    req.getRequestDispatcher("/login.jsp").forward(req, resp);
                } else {
                    //登录成功
                    if(loginUser.getStatus()==1){
                        req.setAttribute("msg", "你不能进入本轮投票！");
                        req.setAttribute("username", username);
                        req.getRequestDispatcher("/login.jsp").forward(req, resp);
                    }else {
                        List<Vote> votes = voteService.queryAllVote(projectId);
                        for (Vote vote : votes) {
                            if (vote.getVoteStatus() == 1) {
                                req.getSession().setAttribute("vote", vote);
                                List<Candidate> candidates = candidateService.queryCandidate(vote.getVoteId());
                                req.getSession().setAttribute("candidates", candidates);
                                break;
                            }
                        }
                        req.getSession().setAttribute("judge", loginUser);
                        req.getRequestDispatcher("/judge/vote.jsp").forward(req, resp);
                    }
                }
            }else{
                req.setAttribute("msg", "项目不存在！");
                req.setAttribute("username", username);
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        }else{
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    protected void manageJudge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Project project = (Project)req.getSession().getAttribute("project");
        List<Judge> judges = judgeService.queryJudge(project.getProjectId());
        req.getSession().setAttribute("judges",judges);
        resp.sendRedirect("user/manage_judge.jsp");
    }

    protected void deleteJudge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Project project = (Project)req.getSession().getAttribute("project");
        String judgeId = req.getParameter("judgeId");
        List<Judge> judgeList = (List<Judge>)req.getSession().getAttribute("judges");
        if(judgeList.size()==1){
            req.setAttribute("msg", "至少一个评委！");
            req.getRequestDispatcher("/user/manage_judge.jsp").forward(req, resp);
        }else {
            judgeService.deleteJudge(Integer.parseInt(judgeId));
            List<Judge> judges = judgeService.queryJudge(project.getProjectId());
            req.getSession().setAttribute("judges", judges);
            resp.sendRedirect("user/manage_judge.jsp");
        }
    }

    protected void addJudge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String judgename = req.getParameter("judgename");
        String judgepassword = req.getParameter("judgepassword");
        Project project = (Project)req.getSession().getAttribute("project");
        String projectId = project.getProjectId();
        if(judgeService.existJudge(judgename,projectId)){
            req.setAttribute("msg", "评委用户名不能重复！");
            req.getRequestDispatcher("/user/manage_judge.jsp").forward(req, resp);
        }else {
            judgeService.createJudge(new Judge(null, judgename, judgepassword, 1, projectId));
            List<Judge> judges = judgeService.queryJudge(projectId);
            req.getSession().setAttribute("judges", judges);
            resp.sendRedirect("user/manage_judge.jsp");
        }
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁session对象
        req.getSession().invalidate();
        //重定向到登录界面
        resp.sendRedirect("login.jsp");
    }
}
